package com.finalab.yueqiu.service.auth;


import com.alibaba.fastjson.JSONObject;
import com.finalab.yueqiu.constant.RedisKeyType;
import com.finalab.yueqiu.constant.ResponseCode;
import com.finalab.yueqiu.dao.auth.UserAuthDAO;
import com.finalab.yueqiu.dao.auth.po.UserAuthPO;
import com.finalab.yueqiu.dao.redis.JedisDAO;
import com.finalab.yueqiu.dao.user.UserDAO;
import com.finalab.yueqiu.dao.user.po.UserPO;
import com.finalab.yueqiu.util.RedisKeyUtil;
import com.finalab.yueqiu.util.communicate.PhoneUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 莉安
 */
@Service
public class AuthServiceImpl implements AuthService{
    @Autowired
    UserAuthDAO userAuthDAO;

    @Autowired
    UserDAO userDAO;

    @Autowired
    JedisDAO jedisDAO;


    private static final String SEND_SUCCEED = "000000";
    private static final int HAVE_AUTH = 1;
    private static final String AUTH_CODE_NAME = "AUTH";
    private static final int TIME_OUT = 300;


    @Override
    public int authPhone(String phone,String param){
        UserAuthPO userAuthPO = userAuthDAO.selectByPhone(phone);
        UserPO userPO = userDAO.selectByPhone(phone);
        if(userAuthPO != null && userPO != null){
            return ResponseCode.ENTITY_ALREADY_EXISTS.getValue();
        }
        if(userAuthPO != null){
            return ResponseCode.ALREADY_HAVE_AUTH.getValue();
        }
        String result = PhoneUtil.sendSms(param,phone,"");
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = (String) jsonObject.get("code");
        if(!SEND_SUCCEED.equals(code)){
            return ResponseCode.SERVER_ERROR.getValue();
        }
        jedisDAO.setex(RedisKeyUtil.getKey(RedisKeyType.AUTH), TIME_OUT, param);
        return ResponseCode.REQUEST_SUCCESSED.getValue();
    }



    @Override
    public int phoneSuccess(String phone, String param){
        UserAuthPO userAuthPO = userAuthDAO.selectByPhone(phone);
        if(userAuthPO == null){
//            String param = jedisDAO.get(AUTH_CODE_NAME);
//            if(param == null){
//                return ResponseCode.TIME_INVALID.getValue();
//            }
//            if(!param.equals(code)){
//                return ResponseCode.PARAM_ILLEGAL.getValue();
//            }
            userAuthDAO.insert(HAVE_AUTH, phone);
            return ResponseCode.REQUEST_SUCCESSED.getValue();
        }
        if(userAuthPO.getPhone() == HAVE_AUTH){
            return ResponseCode.ALREADY_HAVE_AUTH.getValue();
        }
        return ResponseCode.SERVER_ERROR.getValue();
    }

}
